package com.sun.personal.controller;

import com.sun.domain.Result;
import com.sun.domain.ResultCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author syh
 * @date 2021/7/5 10:13
 */

@Controller
public class HelloController {


    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public Result uploadFile(MultipartFile multipartFile, HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Result result = new Result();
        //获得原始文件名
        String filename = multipartFile.getOriginalFilename();
        boolean flag = filename.endsWith(".pdf");
        if (!flag) {
            return result.setMessage("请输入pdf格式的文件").setCode(ResultCode.FAIL);
        }
        String format = sdf.format(new Date());
        String path = request.getServletContext().getRealPath("/") + format;
        File folder = new File(path);
        //文件夹不存在就创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //生成新的文件名
        String newFileName = UUID.randomUUID().toString() + ".pdf";
        try {
            multipartFile.transferTo(new File(folder, newFileName));
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newFileName;
            return result.setData(url).setMessage("上传成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

